import React, { useEffect, useState, useRef } from 'react'
import style from './Index.module.less'
import classNames from 'classnames'
import { awaitWrap } from '@js/tool'
import { getListRequest } from './ajax'
import { Skeleton, Empty } from 'antd'
import Item from './components/Items/Index'
import EditFileModal from './components/EditFileModal/Index'
import { Document, Page } from 'react-pdf'

async function initList (id, setZList, setFList, setLoading, file, setFile) {
  setLoading(true)
  const [e, d] = await awaitWrap(getListRequest(id))
  setLoading(false)
  if (e === null && d !== null) {
    setZList(d.filter(li => li.type === '正卷'))
    setFList(d.filter(li => li.type === '副卷'))
    if (file === null && d.length > 0) {
      setFile(d[0])
    } else if (file !== null) {
      const f = d.find(li => li.id === file.id)
      if (f) {
        setFile(f)
      }
    }
  }
}

// 渲染pdf页面
function renderPages (width, numPages) {
  const arr = []
  for (let i = 0; i < numPages; i++) {
    arr.push((
      <div key={i}>
        <Page pageNumber={i + 1} width={width} renderTextLayer={false} renderAnnotationLayer={false} />
      </div>
    ))
  }
  return arr
}

function renderLoading () {
  return (
    <Skeleton active paragraph={{ rows: 6 }} />
  )
}

function Main ({ meta }) {
  const ref = useRef(null)
  const { title, id } = meta
  const [loading, setLoading] = useState(false)
  const [zList, setZList] = useState([])
  const [fList, setFList] = useState([])
  const [zIds, setZIds] = useState([])
  const [fIds, setFIds] = useState([])
  const [file, setFile] = useState(null)
  const [modifyData, setModifyData] = useState(null)
  const [visible, setVisible] = useState(false)
  const [pages, setPages] = useState(0)
  const [width, setWidth] = useState(0)
  useEffect(() => {
    setZIds(zList.map(li => li.id))
  }, [zList])
  useEffect(() => {
    setFIds(fList.map(li => li.id))
  }, [fList])
  useEffect(() => {
    initList(id, setZList, setFList, setLoading, file, setFile).catch(e => console.error(e))
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [meta, id])
  useEffect(() => {
    function initWidth () {
      const c = ref.current
      if (c !== null) {
        setWidth(c.offsetWidth)
      }
    }
    initWidth()
    window.addEventListener('resize', initWidth)
    return () => {
      window.removeEventListener('resize', initWidth)
    }
  }, [])
  return (
    <div className={style.container}>
      <EditFileModal visible={visible} data={modifyData} hide={() => { setVisible(false); setModifyData(null) }} refreshFn={() => initList(id, setZList, setFList, setLoading, file, setFile).catch(e => console.error(e))} />
      <div className={style['title-line']}>
        <span>归档案号：{title}</span>
      </div>
      <div className={style.body}>
        <div className={style['body-left']}>
          <div className={style['body-left-inner']}>
            <Skeleton loading={loading} active>
              <div className={classNames(style['file-type-title'], { [style.active]: file && zIds.includes(file.id) })}>正卷</div>
              {
                zList.map((li, i) => {
                  return (
                    <Item active={file === li} data={li} key={i} setModifyData={(d) => { setModifyData(d); setVisible(true) }} setFile={d => { setFile(d) }} />
                  )
                })
              }
              <div className={classNames(style['file-type-title'], { [style.active]: file && fIds.includes(file.id) })}>副卷</div>
              {
                fList.map((li, i) => {
                  return (
                    <Item active={file === li} data={li} key={i} setModifyData={(d) => { setModifyData(d); setVisible(true) }} setFile={d => { setFile(d) }} />
                  )
                })
              }
            </Skeleton>
          </div>
        </div>
        <div className={style['body-right']}>
          <div className={style['body-right-inner']} ref={ref}>
            {
              file && file.pdf_file instanceof Array && file.pdf_file.length > 0 ? (
                <Document
                  loading={renderLoading()}
                  file={`${file.pdf_file[0].path}`}
                  onLoadSuccess={e => { setPages(e.numPages) }}
                  error='文书生成失败，请点击“重新生成”操作。'
                  // options={{ cMapUrl: 'cmaps/', cMapPacked: true }}
                >
                  {renderPages(width, pages)}
                </Document>
              ) : (
                <div className={style.empty}>
                  <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description='文件缺失' />
                </div>
              )
            }
          </div>
        </div>
      </div>
    </div>
  )
}

export default Main
